<?php

namespace app\gears\controller;

use app\gears\validate\GearValidate;
use app\index\common\ApiResponse;
use app\index\common\JwtAuth;
use app\index\controller\Base;

class Index extends Base
{
    public function index(){
        $gears = model('Gears');
        $list = $gears->where('type','=',2)->select();
        return ApiResponse::json(200,'succeed',$list);
    }
    public function editGears(){
        $params = request()->param();
        $validate = new GearValidate();
        $isEdit = !empty($params['id']);
        $name = $isEdit?'edit':'add';
        if (!$validate->scene($name)->check($params)) {
            return ApiResponse::json(300,$validate->getError(),null);
        }
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $remark = '';
        if (!empty($params['remark'])){
            $remark = $params['remark'];
        }
        $gears = model('Gears');
        $maxGear = $gears->max('value');
        $maxGear++;
        if($isEdit){
            $gear = $gears::where('id', $params['id'])->find();
            $gear->save([
                'name' => $params['name'],
                'remark' => $remark,
                'ableStartTime' =>$params['ableStartTime'],
                'ableEndTime' =>$params['ableEndTime'],
            ]);
        }else{
            $gears->save([
                'name' => $params['name'],
                'remark' =>$remark,
                'type' => 2,
                'value' =>  $maxGear,
                'ableStartTime' =>$params['ableStartTime'],
                'ableEndTime' =>$params['ableEndTime'],
            ]);
        }
        return ApiResponse::json(200,'操作成功',null);
    }
    public function deleteGears(){
        $params = request()->param();
        $validate = new GearValidate();
        if (!$validate->scene('delete')->check($params)) {
            return ApiResponse::json(300,$validate->getError(),null);
        }
        $jwtAuth = new JwtAuth();
        $payload = $jwtAuth->getPayload($params['token']);
        if($payload['level'] > 2){
            return ApiResponse::json(300,'您还不是管理员',null);
        }
        $gears = model('Gears');
        $gears::get($params['id'])->delete();
        return ApiResponse::json(200,'操作成功',null);
    }
}